package app.inmos.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.StrictMode;
import android.widget.ImageView;
import app.inmos.exception.ImagenNoEncontradaException;



public class ImageUtils {
	
	private static ImageUtils imageUtils;
	
	/**
	 * Singleton de InmobiliariaUtils
	 * @return
	 */
	public static ImageUtils getInstance() {
		
		if (imageUtils == null) {
			imageUtils = new ImageUtils();
		}
		return imageUtils;
		
	}
	
	
	public Bitmap obtenerImagen(String pUrl) throws ImagenNoEncontradaException{
		
		    URL imageUrl;
		    Bitmap loadedImage=null;
	
				
		    try {
		    	
		    	 if (android.os.Build.VERSION.SDK_INT > 9) {
		    	      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    	      StrictMode.setThreadPolicy(policy);
		    	 }
					
		    	 imageUrl = new URL(pUrl);
				
                 HttpURLConnection conn;
			
				 conn = (HttpURLConnection) imageUrl.openConnection();
				 
				 conn.getInputStream();
				 System.out.println(conn.getURL().toString());
				
                 conn.connect();
			
                 loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
		         
                 if(loadedImage==null){
                	 throw new ImagenNoEncontradaException("La imagen no ha sido encontrada");
                 }
                 
		       }
		        
			   catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
			   }
		     
		       catch (IOException e) {
		    	   e.printStackTrace();
		    	   throw new ImagenNoEncontradaException("La imagen no ha sido encontrada");
					
				}
		       
		
			
			return loadedImage;
		 
		
		
	}
	
	public void cargarImagen (ImageView pImageView,Activity pActivity, int pIdImagen, String pUrl){
	
	  ImageView imageView = (ImageView)pActivity.findViewById(pIdImagen);   
      
      try {
      	
			Bitmap bitmap=ImageUtils.getInstance().obtenerImagen(pUrl);
			imageView.setImageBitmap(bitmap);
			
			
			
			
		} catch (ImagenNoEncontradaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      
	}

}
